const express = require('express');
const cors = require('cors');
const userRoutes = require('./userRoutes');
const apiRoutes = require('./apiRoutes');
require('./database'); // 初始化数据库

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
  if (req.method !== 'GET') {
    console.log('请求体:', JSON.stringify(req.body));
  }
  next();
});

// 路由
app.use('/api/users', userRoutes);
app.use('/api', apiRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({ message: '服务器内部错误', error: err.message });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
}); 